package com.ano.controller;

import com.ano.entity.User;
import com.ano.service.UserService;
import com.ano.utils.JWTUtil;
import com.ano.utils.ResultUtil;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cutezha
 * @Data 2020/11/24
 * @description 用户controller，处理对用户操作的各种请求
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;
    
    /**
     * 用户登录发送的请求
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("login")
    public ResultUtil<User> login(User user){
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        ResultUtil<User> res = new ResultUtil<User>();
        try {
            User loginUser = userService.login(user);
            //此map为要传入token的payload的值
            Map map = new HashMap();
            map.put("id",loginUser.getId());
            map.put("username",user.getUsername());
            //创建一个token
            String token = JWTUtil.getToken(map);
            res.setMsg("登录成功！！！").setObj(loginUser).setToken(token);
        } catch (Exception e) {
            /**
             * 可能抛出的异常为：
             * RuntimeException("用户名不存在！！！");
             * RuntimeException("密码错误！！！");
             */
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("register")
    public ResultUtil<User> register(User user){
        ResultUtil<User> res = new ResultUtil<User>();
        try {
            userService.register(user);
            res.setMsg("注册成功！！！");
        } catch (Exception e) {
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 获取前端传来的token解析之后获得id
     * 此处传入的user
     * userimg
     * password
     * sex
     * birth
     * @param user
     * @param token
     * @return
     */
    @ResponseBody
    @PostMapping("modify")
    public ResultUtil<User> modify(User user,String token){
        ResultUtil<User> res = new ResultUtil<User>();
        try {
            //获取token
            DecodedJWT verify = JWTUtil.verify(token);
            String id = verify.getClaim("id").asString();
            String username = verify.getClaim("username").asString();
            user.setId(id);
            userService.modify(user);
            res.setMsg("修改成功！！！").setToken(token);
        }
        /**
         * 如果验证失败，会抛出异常
         * 常见四个异常类型如下
         * SignatureVerificationException  签名不一致
         * TokenExpiredException    令牌过期
         * AlgorithmMismatchException    算法不一致
         * InvalidClaimException     失效的payload
         */
        catch(SignatureVerificationException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");

        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }


    /**
     * 这里应该还要删除其下所有簇
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public ResultUtil<User> delete(String token){
        ResultUtil<User> res = new ResultUtil<User>();
        try {
            DecodedJWT verify = JWTUtil.verify(token);
            String id = verify.getClaim("id").asString();
            userService.delete(id);
            res.setMsg("删除成功！！！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");

        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 通过token解析出id，通过id查询
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping("findById")
    public ResultUtil<User> findById(@RequestParam("token") String token){
        ResultUtil<User> res = new ResultUtil<User>();

        try{
            DecodedJWT verify = JWTUtil.verify(token);
            String id = verify.getClaim("id").asString();
            User user = userService.findById(id);
            res.setMsg("按id查找成功！！！").setObj(user);
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("findByName")
    public ResultUtil<User> findByName(@RequestParam("token") String token){
        ResultUtil<User> res = new ResultUtil<User>();

        try{
            DecodedJWT verify = JWTUtil.verify(token);
            String username = verify.getClaim("username").asString();
            User user = userService.findByName(username);
            res.setMsg("按username查找成功！！！").setObj(user);
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

}
